﻿// 控制器代码保持不变
using Entity;
using IRealize;
using Microsoft.AspNetCore.Mvc;
using Realize;
using System.Threading.Tasks;

namespace WebApplication9.Controllers
{
    public class LeftController : Controller
    {
        private readonly ILogger<LeftController> _logger;
        private readonly IConfiguration _configuration;
        private IEmailService _emailService;

        public LeftController(ILogger<LeftController> logger, IConfiguration configuration, IEmailService emailService)
        {
            _logger = logger;
            _configuration = configuration;
            _emailService = emailService;
        }

        public async Task<IActionResult> Index()
        {
            IUsers us = new Users();
            string rid = HttpContext.Session.GetString("RID");

            // 获取角色对应的权限
            List<RolesJurisdiction> roleJurisdictions = await us.Select3(int.Parse(rid), _configuration["SqlServer"]);

            // 获取所有权限项
            List<Jurisdiction> allJurisdictions = new List<Jurisdiction>();
            foreach (var rj in roleJurisdictions)
            {
                List<Jurisdiction> jurs = await us.Select4(rj.JuriID, _configuration["SqlServer"]);
                allJurisdictions.AddRange(jurs);
            }

            // 构建树形菜单结构
            List<Jurisdiction> menuTree = BuildMenuTree(allJurisdictions);

            return View(menuTree);
        }

        private List<Jurisdiction> BuildMenuTree(List<Jurisdiction> allItems)
        {
            // 处理地址分割
            foreach (var item in allItems)
            {
                if (!string.IsNullOrEmpty(item.JurAddress) && item.JurAddress.Contains("/"))
                {
                    string[] parts = item.JurAddress.Split('/');
                    if (parts.Length >= 2)
                    {
                        item.Controller = parts[0];
                        item.Action = parts[1];
                    }
                }
            }

            // 构建树形结构
            var rootItems = allItems.Where(i => i.GroupID == 0).ToList();

            foreach (var root in rootItems)
            {
                AddChildren(root, allItems);
            }

            return rootItems;
        }

        private void AddChildren(Jurisdiction parent, List<Jurisdiction> allItems)
        {
            var children = allItems.Where(i => i.GroupID == parent.JuriID).ToList();
            if (children.Any())
            {
                parent.Children = children;
                foreach (var child in children)
                {
                    AddChildren(child, allItems);
                }
            }
        }
    }
}